import React from 'react'
import classnames from 'classnames';
import { InputItem, Button, Tools } from 'weaver-mobile';

const getLabel = Tools.getLabel;
const prefixCls = 'email-set-item-input', hiddenCls = 'email-set-item-input-hidden';
export default class SetItemInput extends React.Component {
  constructor(props) {
    super(props)
  
    this.state = {
      value: [],
      inputValue: '',
      selectedKey: '',
      showInput: false,
    }
  }

  componentDidMount() {
    const { value } = this.props;
    this.setState({ value, showInput: !value.length })
  }

  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.value) !== JSON.stringify(this.state.value)) {
      this.setState({ value: nextProps.value, showInput: false })
    }
  }

  render () {
    const { inputValue, showInput, value, selectedKey } = this.state;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-line-show`}>
          <div className={`${prefixCls}-line-show-tag`} onClick={this.onShowInput}>
            <div className={classnames(`${prefixCls}-line-show-tag-item`, value[0] ? '' : hiddenCls, selectedKey === (value[0] && value[0].id) ? `selected` : '')} 
              onClick={(e) => this.setSelectedKey(e, value[0].id)}
            >
              <span>{value[0] && value[0].name}</span>
            </div>
          </div>
          <div className={classnames(`${prefixCls}-line-show-extra`, !showInput ? '' : hiddenCls)}>
            { this.props.extra }
          </div>
        </div>
        <div className={classnames(`${prefixCls}-line-input`, showInput ? '' : hiddenCls)}>
          <div className={`${prefixCls}-line-input-div`}>
            <div>
              {/*用于监听删除事件，触发其它动作时会清除selectedKey*/}
              <InputItem
                className={classnames(selectedKey ? '' : hiddenCls)}
                value={inputValue}
                onChange={this.onChange}
                onClick={this.clearSelectedKey}
                onKeyDown={this.onHideKeyDown}
                ref={(el) => this.hideInputEl = el}
              />
              <InputItem
                className={classnames(!selectedKey ? '' : hiddenCls)}
                value={inputValue}
                onChange={this.onChange}
                onKeyDown={this.onPress}
                ref={(el) => this.inputEl = el}
              />
              <Button
                className={inputValue ? '' : hiddenCls}
                disabled={!inputValue}
                type="primary"
                onClick={this.onSave}
              >
                { value.length > 0 ? getLabel('84563', '替换') : getLabel(826, '确定') }
              </Button>
            </div>
          </div>
          <div className={`${prefixCls}-line-input-extra`}>
            { this.props.extra }
          </div>
        </div>
      </div>
    )
  }

  onHideKeyDown = (e) => {
    if (e.which === 8 || e.which === 46) {
      this.del(e);
      e.preventDefault();
    } else {
      this.clearSelectedKey();
    }
  }

  clearSelectedKey = () => {
    this.setState({selectedKey: ''}, () => {
      this.inputEl.focus();
    });
  }

  setSelectedKey = (e, key) => {
    e.preventDefault();
    e.stopPropagation();

    this.setState({selectedKey: key, showInput: true}, () => {
      this.hideInputEl.focus();
    });
  }

  onShowInput = () => {
    if (!this.state.showInput) {
      this.setState({showInput: true}, () => {
        this.inputEl.focus()
      })
    }
  }

  onChange = (v) => this.setState({ inputValue: v })

  onPress = (e) => {
    if (e.which === 8 || e.which === 13 || e.which === 46) {
      switch(e.which) {
        case 8: this.onDel(e);break;
        case 46: this.onDel(e);break;
        case 13: this.onEnter(e);break;
        default: break;
      }
    }
  }

  del = (e) => {
    if (this.state.selectedKey) {
      this.setState({
        value: this.state.value.filter((item) => item.id !== this.state.selectedKey),
      }, () => {
        this.props.onChange && this.props.onChange(this.state.value);
      });
      this.clearSelectedKey();
    }
  }

  /**
   * 触发删除事件
   * 如果输入框中已被清空，则选中上方的最后一条信息
   * @param e
   */
  onDel = (e) => {
    const {value, inputValue} = this.state;
    if (!inputValue && Array.isArray(value) && value.length > 0) {
      this.setSelectedKey(e, value[value.length - 1].id);
    }
  }

  onEnter = (e) => {
    this.onSave(e);
    e.preventDefault();
  }

  // 保存
  onSave = (e) => {
    let inputValue = this.state.inputValue;
    if (!inputValue) return;

    let value = this.state.value;
    if (value.length === 0) {
      value = [{ id: String(Math.random()).substr(3, 6), name: inputValue, validate: true }]
    } else { // 替换
      value = [{ id: Number(value[value.length-1].id) + 1 + '', name: inputValue, validate: true }]
    }
    this.setState({inputValue: '', value, showInput: false})
    this.props.onChange && this.props.onChange(value);
  }
}